package com.huilian.iotbox.admin.quartz.controller;

import com.huilian.iotbox.admin.quartz.job.BaseJob;
import com.huilian.iotbox.admin.quartz.service.IJobAndTriggerService;
import com.huilian.iotbox.data.common.ServerResponse;
import com.huilian.iotbox.data.quartz.entity.JobAndTrigger;
import lombok.extern.slf4j.Slf4j;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;



@Slf4j
@RestController
@RequestMapping(value = "/api/job")
public class JobController {

    @Resource
    private IJobAndTriggerService iJobAndTriggerService;

    //加入Qulifier注解，通过名称注入bean
    @Autowired
    @Qualifier("Scheduler")
    private Scheduler scheduler;

    /**
     * 获取所有任务 begin
     * */
    @GetMapping(value = "/list")
    public ServerResponse queryjob(@RequestParam(value = "pageNum") Integer pageNum, @RequestParam(value = "pageSize") Integer pageSize) {
        return iJobAndTriggerService.getJobAndTriggerDetails(pageNum, pageSize);
    }
    /**
     * 获取所有任务 end
     * */

    /**
     * 添加任务 begin
     * */
    @PostMapping
    public ServerResponse addjob(@RequestBody JobAndTrigger entity) throws Exception {
        return addJob(entity.getJobName(), entity.getJobClassName(), entity.getJobGroup(), entity.getCronExpression());
    }

    public ServerResponse addJob(String jobName, String jobClassName, String jobGroupName, String cronExpression) throws Exception {
        try {

            // 启动调度器
            scheduler.start();

            //构建job信息
            JobDetail jobDetail = JobBuilder.newJob(getClass(jobClassName).getClass()).withIdentity(jobName, jobGroupName).build();

            //表达式调度构建器(即任务执行的时间)
            CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(cronExpression);

            //按新的cronExpression表达式构建一个新的trigger
            CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity(jobClassName, jobGroupName).withSchedule(scheduleBuilder).build();

            scheduler.scheduleJob(jobDetail, trigger);
            return ServerResponse.createBySuccess();
        } catch (SchedulerException e) {
            return ServerResponse.createByErrorMessage("创建定时任务失败：" + e);
        } catch (Exception e) {
            return ServerResponse.createByErrorMessage("创建定时任务失败：" + e);
        }
    }

    /**
     * 添加任务 end
     * */

    /**
     * 修改任务 begin
     * 只能修改执行时间表达式
     */
    @PutMapping(value = "/reschedule")
    public ServerResponse rescheduleJob(@RequestBody JobAndTrigger entity, HttpServletRequest request) throws Exception {
        try {
            this.jobreschedule(entity.getJobClassName(), entity.getJobGroup(), entity.getCronExpression());
            return ServerResponse.createBySuccess();
        } catch (Exception e) {
            log.error("任务调度出现错误{}", e);
            return ServerResponse.createByErrorMessage("更新任务失败：" + e);
        }
    }
    public void jobreschedule(String jobClassName, String jobGroupName, String cronExpression) throws Exception {
        try {
            TriggerKey triggerKey = TriggerKey.triggerKey(jobClassName, jobGroupName);
            // 表达式调度构建器
            CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(cronExpression).withMisfireHandlingInstructionDoNothing();

            CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey);

            // 按新的cronExpression表达式重新构建trigger
            trigger = trigger.getTriggerBuilder().withIdentity(triggerKey).withSchedule(scheduleBuilder).build();

            // 按新的trigger重新设置job执行
            scheduler.rescheduleJob(triggerKey, trigger);
        } catch (SchedulerException e) {
            System.out.println("更新定时任务失败" + e);
            throw new Exception("更新定时任务失败：" + e);
        } catch (Exception e) {
            System.out.println("更新定时任务失败" + e);
            throw new Exception("更新定时任务失败：" + e);
        }
    }
    /**
     * 修改任务 end
     */


    /**
     * 暂停任务 begin
     */
    @PutMapping(value = "/pause")
    public ServerResponse pausejob(@RequestBody JobAndTrigger entity) throws Exception {
        try {
            jobPause(entity.getJobName(), entity.getJobGroup());
            return ServerResponse.createBySuccess();
        } catch (Exception e) {
            return ServerResponse.createByErrorMessage("暂停任务失败：" + e);
        }
    }
    public void jobPause(String jobClassName, String jobGroupName) throws Exception {
        scheduler.pauseJob(JobKey.jobKey(jobClassName, jobGroupName));
    }
    /**
     * 暂停任务 end
     */




    /**
     * 恢复任务 begin
     */
    @PutMapping(value = "/resume")
    public ServerResponse resumejob(@RequestBody JobAndTrigger entity) {
        try {
            jobresume(entity.getJobName(), entity.getJobGroup());
            return ServerResponse.createBySuccess();
        } catch (Exception e) {
            return ServerResponse.createByErrorMessage("恢复任务失败：" + e);
        }
    }
    public void jobresume(String jobClassName, String jobGroupName) throws Exception {
        scheduler.resumeJob(JobKey.jobKey(jobClassName, jobGroupName));
    }
    /**
     * 恢复任务 end
     */



    /**
     * 删除任务 begin
     */
    @PutMapping(value = "/delete")
    public ServerResponse deletejob(@RequestBody JobAndTrigger entity) {
        try {
            this.jobdelete(entity.getJobName(), entity.getJobGroup());
            return ServerResponse.createBySuccess();
        } catch (Exception e) {
            return ServerResponse.createByErrorMessage("删除任务失败：" + e);
        }
    }
    public void jobdelete(String jobClassName, String jobGroupName) throws Exception {
        scheduler.pauseTrigger(TriggerKey.triggerKey(jobClassName, jobGroupName));
        scheduler.unscheduleJob(TriggerKey.triggerKey(jobClassName, jobGroupName));
        scheduler.deleteJob(JobKey.jobKey(jobClassName, jobGroupName));
    }
    /**
     * 删除任务 end
     */



    public static BaseJob getClass(String classname) throws Exception {
        Class<?> class1 = Class.forName(classname);
        return (BaseJob) class1.newInstance();
    }

}
